package com.strongbj.iot.devices.newlight.response.handle;

import java.util.Timer;
import java.util.TimerTask;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.Constans;
import com.strongbj.iot.devices.newlight.common.NetMapping;
import com.strongbj.iot.devices.newlight.entity.T;
import com.strongbj.iot.devices.newlight.message.NewLightOSMessageFactory;
import com.strongbj.iot.devices.newlight.message.NewLightReaderMessage;
import com.strongbj.iot.devices.newlight.response.common.HandleTimeStamp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

/**
 * 0x31信道状态查询申请
 * @author lei_w
 *
 */
public class ChannelStateApplyResponseHandle implements IMessageHandle<NewLightReaderMessage, Object> {

	private static Logger logger = LogManager.getLogger(ChannelStateApplyResponseHandle.class.getName());
	
	private NewLightOSMessageFactory newLightOSMessageFactory = (NewLightOSMessageFactory) ContextUtils.getBean("newLightOSMessageFactory");
	
	
	@Override
	public boolean isHandle(NewLightReaderMessage t) {
		if (Integer.valueOf("31", 16).byteValue() == t.getType()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightReaderMessage t) {
		String hostNumber = ByteUtil.byteArrToHexString(t.getAddress()); // reader 地址码
		String timeStamp = ByteUtil.byteArrToHexString(t.getTime()); // 时间戳
		
		String priority = ByteUtil.byteArrToHexString(t.getBody(), 0, 1); //申请优先级
		String cycle = ByteUtil.byteArrToHexString(t.getBody(), 1, 1); //申请周期数
		String validity = ByteUtil.byteArrToHexString(t.getBody(), 2, 4);
		//long validity = ByteUtil.bytesToLong(ByteUtil.subBytes(t.getBody(), 2, 4)); //周期有效期 MS
		String log = "\r\n===================================================" +
		"\r\n收到信道状态查询申请报文：" + 
		"\r\nREADER地址码：" + hostNumber + 
		"\r\n申请优先级：" + priority +
		"\r\n申请周期数：" + cycle +
		"\r\n周期有效期 MS：" + Long.valueOf(validity, 16) +
		"\r\n时间戳：" + HandleTimeStamp.handle(timeStamp);
		logger.info(log);
		
		synchronized (Constans.isBusy) {
			if(!Constans.isBusy) {
				//返回空闲
				byte[] sendData = new byte[1];
				sendData[0] = (byte)0x01;
				byte[] req = newLightOSMessageFactory.createNewLightOSMessage(
    					ByteUtil.hexStringToBytes(hostNumber), (byte) 0x31, sendData, T.getTimeStamp());
    			ByteBuf bs  = Unpooled.copiedBuffer(req);
    			NetMapping.getInstance().getChannels().writeAndFlush(bs);
    			//启动释放计时
    			Long disTime = Long.valueOf(validity, 16);
    			Timer timer = new Timer();
		        timer.schedule(new TimerTask() {
		            @Override
		            public void run() {
		                //释放忙碌，变为空闲状态
		            	Constans.isBusy = false;
		            }
		        }, disTime);
				
				
			} else if(Constans.isBusy){
				if(Integer.valueOf(priority) > Constans.priority) {
					Constans.priority = Integer.valueOf(priority);
					//返回空闲
					byte[] sendData = new byte[1];
					sendData[0] = (byte)0x01;
					byte[] req = newLightOSMessageFactory.createNewLightOSMessage(
	    					ByteUtil.hexStringToBytes(hostNumber), (byte) 0x31, sendData, T.getTimeStamp());
	    			ByteBuf bs  = Unpooled.copiedBuffer(req);
	    			NetMapping.getInstance().getChannels().writeAndFlush(bs);
	    			//启动释放计时
	    			Long disTime = Long.valueOf(validity, 16);
	    			Timer timer = new Timer();
			        timer.schedule(new TimerTask() {
			            @Override
			            public void run() {
			                //释放忙碌，变为空闲状态
			            	Constans.isBusy = false;
			            }
			        }, disTime);
				}
				//返回忙碌
				byte[] sendData = new byte[1];
				sendData[0] = (byte)0x00;
				byte[] req = newLightOSMessageFactory.createNewLightOSMessage(
    					ByteUtil.hexStringToBytes(hostNumber), (byte) 0x31, sendData, T.getTimeStamp());
    			ByteBuf bs  = Unpooled.copiedBuffer(req);
    			NetMapping.getInstance().getChannels().writeAndFlush(bs);
			}
		}
		return null;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
